import json
import bottle
import datetime
import Mongo

config_file = open('config.json')
config = json.load( config_file )

class Controller:
	
	def __init__(self):
		self.mongo = Mongo.Mongo()
	
	def list(self, name):
		return bottle.abort(501, name + " :: LIST not implemented yet")

	def find(self, name, field, value):
		entity = self.mongo.find(name, field, value)
		if entity == {}:
			bottle.abort(404, 'No documents')
		#del entity['_id']
		#del entity['timestamp']
		return entity

	def delete(self, table):
		data = bottle.request.body.readline()
		if not data:
			bottle.abort(400, 'No data received')
		parameters = json.loads(data)
		try:
			entity = self.mongo.delete(table, parameters)
			if entity == {}:
				bottle.abort(404, 'No documents')
			return entity
		except ValidationError as ve:
			return bottle.abort(400, str(ve))

	def save(self, table):		
		data = bottle.request.body.readline()
		if not data:
			bottle.abort(400, 'No data received')
		entity = json.loads(data)
		try:
			return self.mongo.save(table, entity)
		except ValidationError as ve:
			return bottle.abort(400, str(ve))
